package com.cskaoyan.service;

import com.cskaoyan.bean.MarketOrder;
import com.cskaoyan.bean.MarketOrderExample;
import com.cskaoyan.bean.MarketUser;
import com.cskaoyan.bean.brand.LoginUserVxData;
import com.cskaoyan.bean.brand.OrderVO;
import com.cskaoyan.bean.brand.UserIndexVO;
import com.cskaoyan.bean.brand.UserInfo;
import com.cskaoyan.mapper.MarketOrderMapper;
import com.cskaoyan.mapper.MarketUserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class VxUserServiceImp implements VxUserService{

    @Autowired
    MarketOrderMapper marketOrderMapper;
    @Override
    public LoginUserVxData login(String username, String password,String host) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password,host);
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            return null;
        }
        Session session = subject.getSession();
        MarketUser marketUsername = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        LoginUserVxData loginUserVxData = new LoginUserVxData();
        UserInfo userInfo = new UserInfo();
        userInfo.setAvatarUrl(marketUsername.getAvatar());
        userInfo.setNickName(username);
        loginUserVxData.setUserInfo(userInfo);
        loginUserVxData.setToken((String) session.getId());
        return loginUserVxData;
    }

    @Override
    public UserIndexVO index() {
        Subject subject = SecurityUtils.getSubject();
        MarketUser marketUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.createCriteria().andUserIdEqualTo(marketUser.getId());
        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(marketOrderExample);
        int unrecv = 0;
        int uncomment = 0;
        int unpaid = 0;
        int unship = 0;
        for (MarketOrder marketOrder : marketOrders) {
            if (marketOrder.getOrderStatus() == 101) {
                unpaid++;
            }
            if (marketOrder.getOrderStatus() == 201) {
                unship++;
            }
            if (marketOrder.getOrderStatus() == 301) {
                unrecv++;
            }
            if (marketOrder.getOrderStatus() == 401) {
                uncomment++;
            }
        }
        return new UserIndexVO(new OrderVO(unrecv,uncomment,unpaid,unship));

    }
}
